package FlowGram.Application.User;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 * This class will create a 
 * User in the program.
 * Must get the username, password 
 * and the file path
 * Must use methods in user manager to create the user path 
 * set the level immediately to beginner
 * do not write user to file until you are saving the user therefore
 * I do not need to delete 
 * @author Sonilaure Cineus
 *
 */
public class CreateUser extends JPanel implements ActionListener{
	/*
	 * This is the String for the button of the Jpanel
	 */
	private static String createUser ="Register"; 
	/*
	 * This represents the field the client will 
	 * type their user name. 
	 */
	private JTextField username; 
	/**
	 * This represents the where the client will type
	 * their password. 
	 */
	private JTextField password;

	/**
	 * This textfield will display the 
	 * where the user wishes their directory.
	 */
	private JTextArea directory; 
	/**
	 * This represents the objects
	 * that will allow the user to pick where 
	 * they wish to save their files. 
	 */
	private JFileChooser file; 

	/**
	 * This is needed if you wish 
	 * to use dialog boxes.  
	 */
	private JFrame main; 
	 /**
	  * Button that will be use
	  * to open the  FileChooser
	  * 
	  */
	private JButton openButton;
	 /**
	  * Instance of the UserManager class
	  * so we can use the methods. 
	  */
	 private UserManager create; 
	 
	    /**
		 * Constructor where we create everything 
		 * and the layout the goes with it. 
		 */
		
	public CreateUser(JFrame j){
		
		main = j; 
		
		username = new JTextField(10);
		username.setActionCommand(createUser);
		username.addActionListener(this); 
		
		password = new JTextField(10);
		password.setActionCommand(createUser);
		password.addActionListener(this);
		
		directory = new JTextArea(3,25);
		directory.setEditable(false);
		directory.setMargin(new Insets(1,1,1,1));
		JScrollPane logScrollPane = new JScrollPane(directory);
		
		JLabel ulabel = new JLabel("Enter the username: ");
		ulabel.setLabelFor(username); 
		
		JLabel plabel = new JLabel("Enter the password: ");
		plabel.setLabelFor(password); 
		
		file = new JFileChooser(); 
		file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		
		create = new UserManager(); 
		
		//Create the Panel layout the will hold
		// the text fields and their labels	
		JPanel text = new JPanel();
		text.setLayout(new BoxLayout(text, BoxLayout.Y_AXIS ));
		text.add(ulabel);
		text.add(username);
		text.add(plabel);
		text.add(password);
		
		//Create button and the Panel that will hold the button
		JPanel button = new JPanel(new GridLayout(0,1));
		JButton createButton = new JButton("Register");
		createButton.setActionCommand(createUser);
		createButton.addActionListener(this);
		openButton = new JButton("Select Directory"); 
		openButton.addActionListener(this); 
		button.add(createButton);
		button.add(openButton); 
		
		//Add the panels creates to Major panel
		add(text);
		add(button); 
		add(logScrollPane); 
		
	}
	
	/**
	 * if the user does not choose a file path then should create default path 
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		File ufile = null; 
		if (e.getSource() == openButton) {
            int returnVal = file.showOpenDialog(CreateUser.this);
 
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                 ufile = file.getSelectedFile();
                //This is where a real application would open the file.
                directory.append("Directory Choosen "+ ufile.getAbsolutePath());
            }else {
                directory.append("Open command cancelled by user.");
            }
		}
		if (createUser.equals(cmd)) {
			String user = username.getText(); 
			String pass = password.getText();
			
			try {
				if(create.UserNameExists(user)){
					JOptionPane.showMessageDialog(main,
					        " Invalid Username Try again.",
					        "Error Message",
					        JOptionPane.ERROR_MESSAGE);
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			 if(ufile== null)
			{	
				// then I input the default file path 
				 String path = "/.autofs/ilab/ilab_users/scineus/UserWork"; 
				 try {
					 if (create.CreateUser(user, pass, path)){
						System.exit(0); 
						}
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(main,
					        " Could not create User with Default path.",
					        "Error Message",
					        JOptionPane.ERROR_MESSAGE);
					e1.printStackTrace();
				} 
			

			}
			 else{
				try {
					if(create.CreateUser(user, pass, ufile.getAbsolutePath()))
					{
						System.exit(0); 
					}
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(main,
					        "Could not create user with chosen directory.",
					        "Error Message",
					        JOptionPane.ERROR_MESSAGE);
					e1.printStackTrace();
				} 
			 }
		}
		
		
	}
	
	   //Must be called from the event dispatch thread.
    protected void resetFocus() {
        password.requestFocusInWindow();
    }
	
	private static void createandShowGUI(){
		
		JFrame frame = new JFrame("Create User");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		
		final CreateUser newContentPane = new CreateUser(frame);
	     newContentPane.setOpaque(true); //content panes must be opaque
	        frame.setContentPane(newContentPane);
	 
	        //Make sure the focus goes to the right component
	        //whenever the frame is initially given the focus.
	        frame.addWindowListener(new WindowAdapter() {
	            public void windowActivated(WindowEvent e) {
	                newContentPane.resetFocus();
	            }
	        });
	 
	        //Display the window.
	        frame.pack();
	        frame.setVisible(true);
	}
	
	 public static void main(String[] args) {
	        //Schedule a job for the event dispatch thread:
	        //creating and showing this application's GUI.
	        SwingUtilities.invokeLater(new Runnable() {
	            public void run() {
	                //Turn off metal's use of bold fonts
	       // UIManager.put("swing.boldMetal", Boolean.FALSE);
	        createandShowGUI();
	            }
	        });
	    }
}
